package soap.entity.bo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import soap.entity.exportbean.BasicTaskPlus;
import soap.entity.po.ExportRecord;
import soap.entity.po.User;
import soap.feign.query.UserQuery;
import soap.feign.service.MSUserServiceFeign;
import soap.service.ExportRecordService;
import soap.utils.ExportExcelTools;

import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * Created by ZhangPY on 2020/6/7
 * Belong Organization OVERUN-9299
 * overun9299@163.com
 * Explain:
 */
public class UserBo extends BasicTaskPlus {


    private MSUserServiceFeign MSUserServiceFeign;

    private UserQuery userQuery;

    private ExportRecordService exportRecordService;

    private String exportRecordId;

    private String filePath;

    public UserBo(MSUserServiceFeign MSUserServiceFeign, UserQuery userQuery, ExportRecordService exportRecordService, String exportRecordId, String filePath) {
        this.MSUserServiceFeign = MSUserServiceFeign;
        this.userQuery = userQuery;
        this.exportRecordService = exportRecordService;
        this.exportRecordId = exportRecordId;
        this.filePath = filePath;
    }

    @Override
    public void run() {

        try {
            /** 生成文件 **/
            String excelFileName = "User-record-" +  System.currentTimeMillis() + "-" + ".xlsx";
            String personListForExport = MSUserServiceFeign.getUserListForExport(userQuery);
            Map map = JSONObject.toJavaObject(JSON.parseObject(personListForExport), Map.class);
            Map data = JSONObject.toJavaObject((JSON) map.get("data"), Map.class);
            List<User> people = JSONArray.parseArray(data.get("records").toString(), User.class);
            FileOutputStream fo = new FileOutputStream(filePath + excelFileName);
            new ExportExcelTools(fo).writeHead(User.class).writeList(people).exportData();
            fo.flush();
            fo.close();

            /** 更新导出记录 */
            ExportRecord exportRecord = new ExportRecord();
            exportRecord.setId(exportRecordId);
            exportRecord.setCompletionDate(LocalDateTime.now());
            exportRecord.setState(1);
            exportRecord.setFilePath(filePath + excelFileName);
            exportRecordService.updateExportRecord(exportRecord);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
